﻿using System;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.Windows.Forms;
using ContractManager.Common.Class;
using ContractManager.Common.FormBase;
using ContractManager.BLL.Business;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;

namespace ContractManager.Lists.Contracts
{
    public partial class FrmTask : XtraFormBase
    {
        #region "Define Variable"
        private readonly BackgroundWorker _loadworker = new BackgroundWorker();
        private int _invId;
        private int _formNo;
        private int _conDetId;
        private string _conDetContent;
        #endregion

        #region "Form Construction"
        public FrmTask()
        {
            InitializeComponent();
            InitializeControls();
            _loadworker.DoWork += loadworker_DoWork;
            _loadworker.RunWorkerCompleted += loadworker_RunWorkerCompleted;
            grvTask.PopupMenuShowing+=GrvContractsOnPopupMenuShowing;
            
        }

        private void GrvContractsOnPopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e)
        {
            if (e.MenuType==GridMenuType.Row)
            {
                popupMenu1.ShowPopup(e.Point);
            }
        }

        #endregion

        #region "Private Method"
        
        private void CheckPer()
        {
            var item = ClsForms.SelectByUserForm(ClsVariable.RoleNo, FormNo);
            if (item == null) return;
            AllowAdd = item.AllowAdd;
            AllowDelete = item.AllowDelete;
            AllowEdit = item.AllowEdit;
            AllowAccess = item.AllowAccess;
            AllowPrint = item.AllowPrint;
        }

        private void LockMenu(bool mnlock)
        {
            btnTask.Enabled = !mnlock && AllowAccess;
            btnPrint.Enabled = AllowPrint;
        }

        private void InitializeControls()
        {
            grdTask.DataSource = bdsMain;
            grdTask.UseEmbeddedNavigator = true;
            grvTask.OptionsBehavior.Editable = false;
            grvDetail.OptionsBehavior.Editable = false;
        }

        public void GetData()
        {
            if (!_loadworker.IsBusy)
            {
                _loadworker.RunWorkerAsync();
                ClsVariable.SetWaitDialogCaption(string.Format("Nạp danh sách {0}...", Text));
            }
        }

        

        private void DoView()
        {
            var frm = new FrmTaskDetail()
            {
                
                ConDetId = _invId,
                AsSysBillStyleId = ClsVariable.AsSysBillStyleId,
                AsSysMyCoYearId = ClsVariable.AsSysMyCoYearId,
                AsPerPersonId = ClsVariable.EmployeeId,
                FormNo = _formNo,

                FormSysBillStyleIdExport = FormSysBillStyleIdExport,
                FormXtraLayoutTemplate = FormXtraLayoutTemplate,
                FormXtraGridLayoutTemplate = FormXtraGridLayoutTemplate,
                FormReportLayoutTemplate = FormReportLayoutTemplate,
                FormDetailVatGridLayout = this.FormDetailVatGridLayout,
                VoucherCate = this.VoucherCate,
                IsPrintAfterSave = this.FormIsPrintAfterSave,
                FormAccountDefault = this.FormAccountDefault,
                FormIsNotValidate = this.FormIsNotValidate,
                Text = String.Format("Thông tin chi tiết kèm công việc {0}", _conDetContent),

                MdiParent = this.MdiParent,
                WindowState = FormWindowState.Maximized
            };
            
            frm.Show();
            frm.Focus();
        }

        
        

        private void DoPrint()
        {
            grdTask.ShowPrintPreview();
        }

        

        #endregion

        #region "Background Worker"

        private void loadworker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var list = ClsContracts.ListDetailByMbId(ClsVariable.MemberBranchId);
                e.Result = list;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
                e.Cancel = true;
            }
        }

        private void loadworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Action a = () =>
            {
                bdsMain.DataSource = (DataTable)e.Result;
            };
            grdTask.Invoke(a);
            ClsVariable.SetWaitDialogCaption(string.Format("Danh sách {0} đã được nạp", Text));
        }
        #endregion

        #region "Form Event"
        private void FrmTaskLoad(object sender, EventArgs e)
        {
            if (Tag == null) return;
            _formNo = Convert.ToInt32(Tag);
            ClsVariable.CreateWaitDialog(ClsVariable.StrCaption, "Vui lòng đợi...");
            ClsVariable.SetWaitDialogCaption("Kiểm tra dữ liệu phân quyền...");
            CheckPer();
            ClsVariable.SetWaitDialogCaption(string.Format("Nạp danh sách {0}...",this.Text));
            GetData();
            ClsVariable.CloseWaitDialog();
            FieldNameId = "ConDetId";
            LockMenu(true);
            grvTask.FocusedRowHandle = GridControl.AutoFilterRowHandle;
            if (!String.IsNullOrEmpty(FormReportLayoutTemplate))
            {
                string filePath = ClsVariable.GetRestoreLayoutFullPath(FormReportLayoutTemplate);
                grvTask.RestoreLayoutFromXml(filePath, DevExpress.Utils.OptionsLayoutBase.FullLayout);
            }
            if (!String.IsNullOrEmpty(FormXtraGridSearchLayout))
            {
                var filePath = ClsVariable.GetRestoreLayoutFullPath(FormXtraGridSearchLayout);
                grvDetail.RestoreLayoutFromXml(filePath, DevExpress.Utils.OptionsLayoutBase.FullLayout);
            }
        }

        private void FrmTaskFormClosing(object sender, FormClosingEventArgs e)
        {
            grdTask.Dispose();
            grdDetail.Dispose();
        }

        private void FrmTaskFormClose(object sender, FormClosedEventArgs e)
        {
            this.Dispose();
            this.Close();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
        }
        #endregion

        #region "Toolbar Event"
        private void TbMenuItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "btnTask"://View Task
                    DoView();
                    break;
                case "btnPrint"://Print Contract
                    DoPrint();
                    break;
                case "btnDesignMasterGrid":
                    ClsVariable.ShowDesignXtraGrid(grdTask);
                    break;
                case "btnDesignDetailGrid":
                    ClsVariable.ShowDesignXtraGrid(grdDetail);
                    break;
                case "btnClose":
                    Close();
                    break;
            }
        }
        #endregion

        #region "Grid Event"
        private void grvTask_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle < 0)
            {
                _invId = 0;
                grdDetail.DataSource = null;
                LockMenu(true);
                return;
            }
            if (grvTask.GetRowCellValue(e.FocusedRowHandle, FieldNameId) == DBNull.Value) return;
            _invId = Convert.ToInt32(grvTask.GetRowCellValue(e.FocusedRowHandle, FieldNameId));
            grdDetail.DataSource = null;
            grdDetail.DataSource = ClsTask.ListDetail(_invId);
            grvDetail.FocusedRowHandle = GridControl.AutoFilterRowHandle;
            LockMenu(false);
        }

        
        #endregion
        

    }
}
